package cn.blb.service.edu.listener;

import cn.blb.service.edu.entity.ExcelSubjectData;
import cn.blb.service.edu.service.SubjectService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {
    // servie对象
    private SubjectService subjectService;
    // 1000条数据存一次数据
    private static final Integer BATCH_SIZE = 1000;
    // 数据集合
    private List<ExcelSubjectData> list = new ArrayList<>();

    // 有参构造
    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }


    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        list.add(excelSubjectData);
        if (list.size() >= BATCH_SIZE) {
            // 1.调用方法
            subjectService.saveOneSubject(list);
            // 2.清空list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        subjectService.saveOneSubject(list);
    }
}
